<template>
  <div v-if="flag" class="tag-select-container">
    <el-cascader
      v-select-scroll="!collapseTags"
      v-if="mode === 'create'"
      ref="cascaderSelect"
      v-model="tagData"
      :options="tagTreeList"
      :disabled="disabled"
      :props="{
        emitPath: false,
        value: 'id',
        label: 'name',
        children: 'item',
        multiple: true,
      }"
      :show-all-levels="false"
      :class="!collapseTags?'multiply-select-scroll':'tag-cascader'"
      :collapse-tags="collapseTags"
      :filterable="!disabled"
      size="small"
      popper-class="ellips-cascader"
      placeholder="请选择标签"
      clearable>
      <template slot-scope="{ data }">
        <ToolTip v-if="data.name.length > 15" :content="data.name"/>
        <span v-else>{{ data.name }}</span>
      </template>
    </el-cascader>
    <div v-else-if="mode === 'detail'">
      <div v-if="showMode !== 'string' && tag && tag.length > 0" class="labels">
        <span v-for="(item, index) in tag" :key="index" class="item-wrap">
          <ToolTip v-if="item.name.length > 20" :content="item.name">
            <el-tag :style="item.color ? `color:${item.color} !important;background:${changeColorAlphaVal(item.color, 0.14)} !important;` : ''" plain size="mini" class="ellipsisOne" style="max-width: 200px;">{{ item.name }}</el-tag>
          </ToolTip>
          <el-tag v-else :style="item.color ? `color:${item.color} !important;background:${changeColorAlphaVal(item.color, 0.14)} !important;` : ''" plain size="mini">{{ item.name }}</el-tag>
        </span>
        <div v-if="isShowEditBtn" class="button-text edit-btn" @click="handelClickEdit(tag)">编辑</div>
      </div>
      <div v-else :class="{'has-extend-btn': isShowEditBtn}" class="flex-center">
        <ToolTip :content="handelArr(tag, 'name')" style="margin-right: 5px;" />
        <div v-if="isShowEditBtn" style="flex-shrink: 0;" class="button-text" @click="handelClickEdit()">编辑</div>
      </div>
    </div>
    <div v-else-if="mode === 'list'">
      <el-tooltip v-if="tag && tag.length" placement="top" effect="dark">
        <div slot="content" style="max-width:300px">{{ handleStr(tag) }}</div>
        <div class="tag-wrap">
          <span v-for="(t,index) in handleThreeTag(tag)" :key="index" :style="t.color ? `color:${t.color} !important;background:${changeColorAlphaVal(t.color, 0.14)} !important;` : ''" class="tag">
            {{ t.name }}
          </span>
          <div v-if="tag.length > 3">...</div>
        </div>
      </el-tooltip>
      <div v-else>--</div>
    </div>
  </div>
</template>

<script>
/**
 * 新建页面标签选择和详情页展示
 */
// api
import { getTagAll } from '@/api/config';
import { TAG_MODULES } from '@/utils/const';
import { isNodeIdExistInTree } from '@/views/resource/create/resourceData';
import ElMessage from '@/utils/message';
import { changeColorAlphaVal } from '@/utils/tools';

export default {
  model: {
    prop: 'tag',
    event: 'changeTag'
  },
  props: {
    tag: {
      type: Array,
      default: () => {
        return [];
      }
    },
    mode: {
      type: String,
      default: 'create'
    },
    collapseTags: {
      type: Boolean,
      default: true
    },
    showMode: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    moduleType: { // 标签所属模块
      type: Number,
      default: null
    },
    isShowEditBtn: {
      type: Boolean,
      default: false
    },
    defaultTagList: {
      type: Array,
      default: null
    },
    platform: { // 标签适用平台
      type: Number | null,
      default: null
    },
    needPlatFormParams: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      TAG_MODULES,
      tagTreeList: [],
      flag: true,
      requestDone: false
    };
  },
  computed: {
    tagData: {
      get() {
        if (this.tag && this.tag.length) {
          return this.tag.map(i => i && i.id);
        }
        return [];
      },
      set(newVal) {
        let tag = [];
        if (newVal && newVal.length > 0) {
          tag = this.getTags(this.tagTreeList, newVal);
        }
        this.$emit('changeTag', tag);
      }
    }
  },
  watch: {
    platform(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        this.queryTagTreeList();
      }
    },
    tag: {
      handler(val, oldVal) {
        if (this.limit && val && val.length > 3) {
          this.$message.warning('标签最多可选择3个');
          this.$emit('changeTag', oldVal || []);
          return;
        }
        if (val && JSON.stringify(val) !== JSON.stringify(oldVal)) { this.handleTags(); }
      },
      immediate: true
    }
  },
  created() {
    if (this.mode === 'create') {
      if (this.defaultTagList && this.defaultTagList.length > 0) {
        this.tagTreeList = this.defaultTagList;
      } else {
        this.queryTagTreeList();
      }
      if (!this.moduleType && this.moduleType !== 0) {
        throw new Error('请传入标签对应的模块类型！');
      }
    }
  },
  methods: {
    changeColorAlphaVal,
    // 获取所有标签
    queryTagTreeList() {
      const params = {
        type: (this.moduleType || this.moduleType === 0) ? this.moduleType : this.TAG_MODULES.GLOBAL
      };
      if (this.platform) {
        params.platform = this.platform;
      }
      this.requestDone = false;
      if (this.needPlatFormParams && !this.platform) return;
      getTagAll(params).then(res => {
        this.requestDone = true;
        this.tagTreeList = (res && res.data) || [];

        if (this.platform && this.tagTreeList.length === 0) {
          ElMessage.warning('该平台下无可选标签，请联系签约经纪处理');
        }
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
        this.flag = false;
        this.$nextTick(() => {
          this.handleTags();
          this.flag = true;
        });
        this.$emit('setTagTreeList', this.tagTreeList);
      });
    },
    getTags(tags, tagIds) {
      const res = [];
      const dfs = (list, id) => {
        if (tags && tags.length) {
          list.forEach(j => {
            if (j.item && j.item.length > 0) {
              dfs(j.item, id);
            }
            if (id === j.id) {
              res.push({
                id: j.id,
                name: j.name
              });
            }
          });
        }
      };
      tagIds.forEach((id) => {
        dfs(tags, id);
      });
      return res;
    },
    handelArr(arr, key) {
      if (!arr || arr.length === 0) return '';
      return arr.map(i => i.name).join(',');
    },
    handelClickEdit(tags = []) {
      this.$emit('handelClickEdit', tags);
    },
    // 移除禁用或者删除的标签
    handleTags() {
      if (this.requestDone && this.platform && this.tagTreeList.length === 0) {
        this.$emit('changeTag', []);
      }
      if (this.mode !== 'create' || !this.tagTreeList.length) return;
      const tags = _.cloneDeep(this.tag);
      if (!tags) return;
      for (let i = 0; i < tags.length; i++) {
        tags.forEach(el => {
          if (!isNodeIdExistInTree(el.id, this.tagTreeList, 'item')) {
            tags.splice(tags.findIndex(j => j.id === el.id), 1);
            i--;
          }
        });
      }
      this.$emit('changeTag', tags);
    },
    clearTags() {
      this.tagTreeList = [];
    },
    handleThreeTag(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.slice(0, 3);
    },
    handleStr(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.map(el => el.name).join(',');
    }
  }
};
</script>

<style lang="scss" scoped>
.tag-select-container {
  width: 100%;
  &::v-deep {
    .el-tag.el-tag--info {
      color: #406eff;
      background: #eff3fb;
    }
    .el-tag--light {
      border: 0;
      padding: 0 8px;
      height: 20px;
      line-height: 20px;
    }
    .el-cascader__tags{
      .el-cascader__search-input{
        height: 22px !important;
      }
    }
  }
}
.edit-btn {
  line-height: 20px;
  display: flex;
  align-items: center;
  height: 20px;
}
.tag-cascader{
  height: 32px;
  &::v-deep {
    .el-input{
      height: 32px;
      .el-input__inner {
        height: 32px !important;
      }
    }
    .el-cascader__tags{
      .el-cascader__search-input{
        height: 28px !important;
      }
      input{
        width: auto !important;
      }
      .el-tag{
        margin-top: 7px !important;
        max-width: 70px;
      }
    }
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.labels{
  display: flex;
  flex-wrap: wrap;
  padding-top: 5px;
}
.item-wrap{
  display: flex;
  margin-right: 5px;
  height: 24px;
}
.has-extend-btn {
  ::v-deep {
    .tooltip-container {
      max-width: 85%;
    }
  }
}
.tag-wrap{
  display: flex;
  align-items: center;
  .tag{
    display: inline-block;
    max-width: 60px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color:#406EFF;
    font-size: 12px;
    height: 20px;
    line-height: 20px;
    padding: 0px 8px;
    margin-right: 4px;
    border-radius: 4px;
    background: #eff4ff;
  }
}
</style>
